//
//  SearchViewController.m
//  MusicPlayer
//
//  Created by dlios on 15-5-25.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//
#import "RecommendLatestModel.h"
#import "SearchViewController.h"
#import "SANetWorkingTask.h"
#import <AFNetworking.h>
#import "searchModel.h"
#import "searchTableViewCell.h"
#import "PlayMusicViewController.h"

@interface SearchViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
@property (nonatomic, retain) UITableView * searchView;
@property (nonatomic, retain) NSMutableArray * searchArray;
@property (nonatomic, retain) NSMutableDictionary * searchDic;
@property (nonatomic, retain) UISearchBar * search;
@property (nonatomic, retain) NSMutableArray * playUrlArray;
@property (nonatomic, retain) NSMutableArray * songListArray;

@end

@implementation SearchViewController
- (void)dealloc
{
    [_songListArray release];
    [_searchBarText release];
    [_searchView release];
    [_searchArray release];
    [_searchDic release];
    [_playUrlArray release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.searchArray = [NSMutableArray array];
        self.searchDic = [NSMutableDictionary dictionary];
        self.playUrlArray = [NSMutableArray array];
        self.songListArray = [NSMutableArray array];
    }
    return self;
}
- (void)loadView
{
    [super loadView];
    
//    点击空白处隐藏键盘
    self.navigationController.title = @"搜索";
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    
//    搜索页面背景图片
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    [imageView setImage:[UIImage imageNamed:@"sou.jpg"]];
    [self.view addSubview:imageView];
    [imageView release];
    
    //    调用搜索方法
    [self searchBar];
    //        调用创建tableview方法
    [self searchTable];

 
}

//点击空白隐藏键盘方法
-(void)viewTapped:(UITapGestureRecognizer*)tapGr
{
    [self.search resignFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIBarButtonItem *exits = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(exitsAction:)];
    self.navigationItem.leftBarButtonItem = exits;
    
}


#pragma mark - 返回图片的事件
- (void)exitsAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

//搜索按钮
- (void)searchBar
{
    self.search = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    [self.view addSubview:self.search];
    self.search.placeholder = @"歌曲/歌手";
    
//    点击按钮弹出键盘
    [self.search becomeFirstResponder];
    self.search.delegate = self;
    
    [self.search release];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.searchBarText = self.search.text;
}

//点击搜索按钮进行网络请求
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    // 字符串 拼接
    NSString *str = [NSString stringWithFormat:@"http://so.ard.iyyin.com/s/song_with_out?q=%@&page=1&size=100", self.searchBarText];
    
    NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    // 网络请求数据
//    AFHTTPSessionManager *mamager = [AFHTTPSessionManager manager];
//    mamager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:address parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.searchArray removeAllObjects];
        NSData *data = [NSData dataWithData:responseObject];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray * array = [dic objectForKey:@"data"];
        for (NSDictionary * dic  in array) {
            RecommendLatestModel * model = [[RecommendLatestModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            model.singerName = model.singer_name;
            [self.searchArray addObject:model];
            //            取音乐网址
            NSArray * arr = [dic objectForKey:@"url_list"];
            if (arr.count >= 2) {
                NSDictionary * dic1 = [arr objectAtIndex:1];
                NSString * url = [dic1 objectForKey:@"url"];
                [self.playUrlArray addObject:url];
                //                NSLog(@"playUrlArray = %@", self.playUrlArray);
            }
            [self.searchView reloadData];
            
        }

    } failure:nil];
  /*
    [manager GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        //        NSLog(@"success");
        
        NSData *data = [NSData dataWithData:responseObject];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray * array = [dic objectForKey:@"data"];
         for (NSDictionary * dic  in array) {
            RecommendLatestModel * model = [[RecommendLatestModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            model.singerName = model.singer_name;
            [self.searchArray addObject:model];
//            取音乐网址
            NSArray * arr = [dic objectForKey:@"url_list"];
            if (arr.count >= 2) {
                NSDictionary * dic1 = [arr objectAtIndex:1];
                NSString * url = [dic1 objectForKey:@"url"];
                [self.playUrlArray addObject:url];
//                NSLog(@"playUrlArray = %@", self.playUrlArray);
            }
             [self.searchView reloadData];

        }
     
    }failure:^(NSURLSessionDataTask *task, NSError *error) {
        //        NSLog(@"failure");
    }];
    */
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.search resignFirstResponder];
    
}

//创建tableView
-(void)searchTable;
{
    self.searchView = [[UITableView alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];
    self.searchView.rowHeight = 70;
    self.searchView.alpha = 0.5;
    self.searchView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.searchView.dataSource = self;
    self.searchView.delegate = self;
    [self.view addSubview:self.searchView];
    
}

//tableView遵循的协议
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentify = @"cell";
    searchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (!cell) {
        cell = [[[searchTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentify] autorelease];
    }
    
    searchModel * modeldic = [self.searchArray objectAtIndex:indexPath.row];
    NSLog(@"array = %ld", self.searchArray.count);
    //    cell.numLabel.text = [NSString stringWithFormat:@"%@",modeldic.artist_flag];
    cell.singLabel.text = modeldic.singer_name;
    cell.songLabel.text = modeldic.song_name;
    
    return cell;
}

//点击进入下一页

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PlayMusicViewController * playMusic = [[PlayMusicViewController alloc]init];
    RecommendLatestModel * model = [self.searchArray objectAtIndex:indexPath.row];
    NSString * str = [self.playUrlArray objectAtIndex:indexPath.row];
    model.singer_name = model.singerName;
    playMusic.songName = model.song_name;
    playMusic.singer = model.singerName;
    playMusic.songUrl = str;
    playMusic.songArray = self.playUrlArray;
    playMusic.songListArray = self.searchArray;
    playMusic.num = indexPath.row;
    
       [self.navigationController pushViewController:playMusic animated:YES];
    [playMusic release];
    
}
@end

